package cn.tedu.micro.demo.emqx.mqtt;

import cn.tedu.micro.demo.emqx.serialize.MessageSerializer;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class MqttProducer<T> {
    @Autowired
    private MqttClient mqttClient;
    //将消息序列化器注入
    @Autowired
    private MessageSerializer<T> messageSerializer;
    //给业务调用者提供一个更符合业务要求的方法
    public void send(String topic,T msg){
        this.send(topic,msg,null,null);
    }
    //封装一个完整参数的方法
    public void send(String topic,T msg,Integer qos,Boolean retained){
        if (qos==null){
            qos=1;
        }
        if (retained==null){
            retained=true;
        }
        //对msg消息做序列化
        byte[] body = messageSerializer.serialize(msg);
        try {
            mqttClient.publish(topic, body, qos, retained);
        }catch (Exception e){
            log.error("发送消息失败",e);
        }
    }
}
